<!DOCTYPE html>
<html lang="en" style="width:100%;height:100%">

<head>
    <meta charset="UTF-8">
    <!--    <name>图层配置</name>-->
    <title>场景编辑</title>
    <link href="../../component/layui/css/layui.css" rel="stylesheet" />
    <link href="../../admin/css/pearCommon.css" rel="stylesheet" />
    <link href="./sceneConfig.css" rel="stylesheet" />
    <link href="../../view/iconfont/iconfont.css" rel="stylesheet">
    <script src="../../component/layui/layui.js"></script>
    <script src="../../lib/jquery/jquery-3.5.1.min.js"></script>
    <script src="../../view/iconfont/iconfont.js"></script>
    <style type="text/css">
        .icon {
            width: 1em;
            height: 1em;
            vertical-align: -0.15em;
            fill: currentColor;
            overflow: hidden;
        }
    </style>
</head>

<body style="width:100%;height: 100%">
    <div id="head">
        <!--    <div style="color: white;font-size: 26px;margin-left: 35px;height:50px; line-height:50px; "> 图层</div>-->
        <!--    <div id="layerFonts" > <span class="layerFonts">图层管理</span></div>-->
        <div class="back">
            <div class="layerBack" id="layerBack">
                <span class="iconfont iconsign_out" style="color: #FFFFFF;width:20px;height:22px;font-size: 20px;"></span>
                <!-- <svg class="icon" aria-hidden="true" >
                <use xlink:href="#icon-sign_out"></use>
            </svg>-->
                <!--            <img src="img/mini.png " style="position: relative; width:30px;margin:10px;">-->
            </div>
        </div>
        <div class="sceneManage" id="sceneManage">
            <div class="sceneManageFonts">场景管理</div>
        </div>
        <div class="sceneNavigate" id="sceneNavigate">
            <div class="sceneNavigateFonts">场景导览</div>
        </div>
    </div>
    <div id="content">
        <div id="leftBar">
            <div id="left-scene">
                <a class="logo_scene" id="logo_scene"><img class="layer_off" id="layer_off" src="img/layer_off.png" style=" width:30px;margin:13px;display:block"></a>
                <a class="logo_scene_on" id="logo_scene_on"><img class="layer_on" id="layer_on" src="img/layer_on.png " style="width:30px;margin:13px;display:none"></a>
            </div>
            <div id="left-layer">
                <a class="logo_layer" id="logo_layer"><img class="layerConfig_off" src="img/data_info_off.png " style="width:30px;margin:13px;display:block"></a>
                <a class="logo_layer_on" id="logo_layer_on"><img class="layerConfig_on" src="img/data_info_on.png " style="width:30px;margin:13px;display:none"></a>
            </div>
        </div>
        <div id="layerContent" style=" display: flex;">
            <iframe class="" id="layer_iframe" name="container" src="../../sceneManage.html" style="position: relative;width:100%;height:100%;border: none;"></iframe>
        </div>
        <div id="layer">
            <div id="layer_parameters">
                <span style="position: absolute;width:56px; height:20px;font-family: PingFangSC-Regular;font-size: 14px;color: #333333;margin-left:16px;top:18px">图层参数</span>
                <!--                <span style="position: relative; width:30px; margin-left:20px; font-size: 18px;">图层配置</span>-->
                <a class="logo_close" id="logo_close">
                    <span class="iconfont icondelete" style="position:relative; width:20px;margin-left:228px;margin-right:16px;top:18px;"></span>
                    <!--                <img src="img/mini.png " style="position:relative; width:20px;margin-left:228px;margin-top:18px;background-color:gray">-->
                </a>
                <hr style="height:1px; width:224px;border:none;border-top:1px; background: #E0E0E0; margin-left:16px; margin-right:16px;margin-top:40px;" />
            </div>
            <div id="layer_item">
                <div class="layer_add" id="layer_add">
                    <span class="iconfont iconadd" style="position: relative; font-family: PingFangSC-Regular;font-size: 14px;color: #FFFFFF;">添加图层</span>
                    <!--                <img src="img/add.png " style="position: relative; width:30px;float:left; ">-->
                </div>
                <div class="layer_create" id="layer_create" style="display:none">
                    <div class="search_add" id="search_add" style="height:36px; width:199px; top: 53px;margin-left: 16px;background: #E6F4FF;border-radius: 4px 4px 0px 0px;margin-top:4px">
                        <span style="position: relative;width:72px; height:17px;font-family: PingFangSC-Regular;font-size: 12px;color: #333333;margin-left:12px;top:10px;">通过搜索添加</span>
                    </div>
                    <div class="spatialModel_add" id="spatialModel_add" style="height:36px; width:199px;margin-left: 16px;background: #FFFFFF;border-radius: 0 0 4px 4px;">
                        <span style="position: relative;width:72px; height:17px;font-family: PingFangSC-Regular;font-size: 12px;color: #333333;margin-left:12px;top:10px;">创建空间模型</span>
                    </div>
                </div>
                <!--                        <a class="layer_add" id="layer_delete"><img src="img/delete.png " style="position: relative; width:20px;float:right;"></a>-->
                <!--                        <legend>图层</legend>-->
                <div class="demo-tree" id="treeLi">
                </div>
            </div>
        </div>
        <div id="layerConfig">
            <div id="layerConfig_on">
                <span style="position: absolute;width:56px; height:20px;font-family: PingFangSC-Regular;font-size: 14px;color: #333333;margin-left:16px;top:18px">修改信息</span>
                <!--                <span style="position: relative; width:30px; margin-left:20px; font-size: 18px;">图层配置</span>-->
                <a class="layer_close" id="layer_close">
                    <span class="iconfont icondelete" style="position:relative; width:20px;margin-left:228px;margin-right:16px;top:18px;"></span>
                    <!--                <img src="img/mini.png " style="position:relative; width:20px;margin-left:228px;margin-top:18px;background-color:gray">-->
                </a>
                <hr style="height:1px; width:224px;border:none;border-top:1px; background: #E0E0E0; margin-left:16px; margin-right:16px;margin-top:40px;" />
            </div>
            <div id="layerConfig_content">
                <span style="position: absolute;width:56px; height:20px;font-family: PingFangSC-Regular;font-size: 14px;color: #333333;margin-left:16px;top:25px">场景封面</span>
                <div class="coverSet" id="coverSet">
                    <div class="coverPhoto" id="coverPhoto">
                        <!--                <div class="coverPhoto" id="coverPhoto" style=" position:relative;width:104px; height:104px;margin-left:16px;margin-top:56px;background: #000;">-->
                        <!--                    <img id="coverScene" src='http://zxc8836.top:8080/one/file/preview/url?url=ff86bf7725f54c57b679c096aedf9450.jpeg' alt="请设置封面" style="width:104px; height:104px;margin-left:16px;margin-top:56px; z-index:20;opacity:0.6; filter: alpha(opacity=60);">-->
                        <img alt="请设置封面" id="coverScene" src='./img/default.jpg' style="width:104px; height:104px;margin-left:16px;margin-top:56px; z-index:20;">
                    </div>
                    <span style="position: absolute;width:112px; height:34px;font-family: PingFangSC-Regular;font-size: 12px;color: #666666;margin-left:128px;top:56px">将当前视角截图设置为场景封面。</span>
                    <span id="setCover" style="position: absolute;cursor: pointer;width:56px; height:20px;font-family: PingFangSC-Regular;font-size: 14px;color: #1563D1;letter-spacing: 0;text-align: center;margin-left:128px;top:137px">设置封面</span>
                </div>
                <span style="position: absolute;width:56px; height:20px;font-family: PingFangSC-Regular;font-size: 14px;color: #333333;margin-left:16px;top:174px">场景视角</span>
                <div class="angleSet" id="angleSet">
                    <div class="anglePhoto" id="anglePhoto">
                        <img id="angleScene" src='./img/default.jpg' style="width:104px; height:104px;margin-left:16px;margin-top:44px;z-index:21;">
                    </div>
                    <span style="position: absolute;width:112px; height:34px;font-family: PingFangSC-Regular;font-size: 12px;color: #666666;margin-left:128px;top:204px">将当前区域设置为初始视角，下次进入场景后将自动飞行至该视角。</span>
                    <span id="setAngle" style="position: absolute;cursor: pointer;width:84px; height:20px;font-family: PingFangSC-Regular;font-size: 14px;color: #1563D1;letter-spacing: 0;text-align: center;margin-left:128px;top:288px">设置初始视角</span>
                </div>
            </div>
        </div>
    </div>
    <div class="site-text" id="service-window" style="margin: 5%; display: none" target="test123">

        <form class="layui-form" id="service-add">
            <div class="layui-form-item" id="research">
                <!--            <hr/>-->
                <!--            <div class="layui-col-md6">-->
                <div class="layui-input-block" style="display:inline-block;width:200px; float:left; margin-left: 15px">
                    <select id="selectFeature" lay-filter="selectFeature" lay-verify="" name="selectFeature">
                    <option value="">请选择添加一种要素类型</option>
                    <option value="1">自定义要素</option>
                    <option value="2">远程服务要素</option>
<!--                    <option value="3" selected="">业务要素</option>-->
                    <option value="4">空间模型要素</option>
                </select>
                </div>
                <label class="layui-form-label">要素名称</label>
                <div class="layui-input-inline">
                    <input class="layui-input" id="demoReload" name="elementName" placeholder="" type="text">
                </div>
                <a class="pear-btn pear-btn-md pear-btn-primary" data-type="reload" id="featureSearch" lay-filter="user-query">
                    <i class="layui-icon layui-icon-search"></i> 查询
                </a>
                <!--            <button type="reset" class="pear-btn pear-btn-md">
                <i class="layui-icon layui-icon-refresh"></i>
                重置
            </button>-->
            </div>
            <div class="layui-form-item">
                <div class="layui-card">
                    <div class="layui-card-body" id="user">
                        <table id="user-table" lay-filter="user-table"></table>
                    </div>
                </div>
            </div>
        </form>

    </div>

</body>
<script id="data-type" type="text/html">
    {{#if (d.type == 1) { }}
    <span>自定义要素</span> {{# }else if(d.type == 2){ }}
    <span>远程服务要素</span> {{# }else if(d.type == 3){ }}
    <span>业务要素</span> {{# }else if(d.type == 4){ }}
    <span>空间模型要素</span> {{# } }}
</script>
<script src="sceneConfig.js"></script>
<script>
    var iframe = document.querySelector("iframe");

    function getUrlParam(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
        var r = window.location.search.substr(1).match(reg); //匹配目标参数
        if (r != null) return unescape(r[2]);
        return null; //返回参数值
    }

    var sceneId;

    sceneId = getUrlParam("sceneId")
    $("#layer_iframe").attr("src", "../../sceneManage.html?sceneId=" + sceneId)



    iframe.onload = function() {
        window.main()
        var layerConfigObj = {};
        var featureId;
        var canSearchAdd = true;
        var featureType;
        var featureName;
        var checkedType;
        var dataT = [];
        var sceneDetail;
        var childWindow = $("#layer_iframe")[0].contentWindow;

        $.ajax({
            url: "/one/scene/detail",
            type: "GET",
            dataType: "json",
            contentType: "application/json; charset=UTF-8",
            data: {
                id: sceneId
            },
            success: function(result) {
                if (result.errorCode === '401') {
                    loginStatusIntercept(result.msg)
                    return
                }
                sceneDetail = result.data;
                if (result.data.coverUrl) {
                    $("#coverScene").attr("src", "/one/file/preview/url?url=" + result.data.coverUrl)
                }
                if (result.data.angleUrl) {
                    $("#angleScene").attr("src", "/one/file/preview/url?url=" + result.data.angleUrl)
                }


            }
        });


        layui.use(['tree', 'util', 'table', 'form'], function() {
            let table = layui.table;
            let form = layui.form;
            var tree = layui.tree,
                layer = layui.layer,
                util = layui.util
                //启用图层
                //模拟数据2
                ,
                data2 = [{
                    "id": 3,
                    "sceneId": 14,
                    "title": "物业权属",
                    "elementId": 89,
                    "type": "1",
                    "checked": "1",
                    "sort": 0
                }];
            layerConfigObj.start = function(data, checkedType) {
                data.checked = checkedType;
                $.ajax({
                    url: "/one/scene/element",
                    type: "PUT",
                    dataType: "json",
                    contentType: "application/json; charset=UTF-8",
                    data: JSON.stringify({
                        elementId: data.elementId,
                        id: data.id,
                        sceneId: sceneId,
                        layerName: data.title,
                        sort: data.sort,
                        status: data.checked ? 1 : 0,
                        type: data.type
                    }),
                    success: function(result) {
                        if (result.errorCode === '401') {
                            loginStatusIntercept(result.msg)
                            return
                        }
                        if (result.errorCode == 0) {
                            // layer.msg("启用图层成功", {icon: 6});
                            // console.log(result.status);
                            // tree.reload('treeId', {data: getData()});
                        } else {
                            // layer.msg("启用图层失败，请检查图层对应的要素内容是否为空", {icon: 5});
                        }
                    }
                });
            };
            //禁用图层
            layerConfigObj.close = function(data, checkedType) {
                data.checked = checkedType;
                $.ajax({
                    url: "/one/scene/element",
                    type: "PUT",
                    dataType: "json",
                    contentType: "application/json; charset=UTF-8",
                    data: JSON.stringify({
                        elementId: data.elementId,
                        id: data.id,
                        sceneId: sceneId,
                        layerName: data.title,
                        sort: data.sort,
                        status: data.checked ? 1 : 0,
                        type: data.type
                    }),
                    success: function(result) {
                        if (result.errorCode === '401') {
                            loginStatusIntercept(result.msg)
                            return
                        }
                        console.log(result);
                        if (result.errorCode == 0) {
                            layer.msg("禁用图层成功", {
                                icon: 6
                            });
                            // data.status = 0;
                            // console.log(result);
                        } else {
                            layer.msg("禁用图层失败，请检查图层对应的要素内容是否为空", {
                                icon: 5
                            });
                        }
                    }
                });
            };
            //图层预览
            layerConfigObj.preview = function(obj) {
                var data = obj.data;
                try {
                    $.ajax({
                        url: "/one/scene/elementInfo",
                        type: "GET",
                        dataType: "json",
                        contentType: "application/json; charset=UTF-8",
                        data: {
                            id: data.id
                        },
                        success: function(result) {
                                if (result.errorCode === '401') {
                                    loginStatusIntercept(result.msg)
                                    return
                                }
                                if (result.errorCode == 0) {
                                    var type = result.data.serviceType;
                                    var previewUrl = result.data.elementContent;
                                    // console.log(previewUrl);
                                    var jumpUrl = "";
                                    childWindow = $("#layer_iframe")[0].contentWindow; //调用iframe页面
                                    // 判断添加的服务地址是否为geoserver发布的服务
                                    if (type == 4) {
                                        jumpUrl = previewUrl;
                                        // jumpUrl =  previewUrl.substr(previewUrl.indexOf("geoserver")-1);//jumpUrl通过geoserver截断解决跨域问题
                                        childWindow.loadGeoJson(jumpUrl, data.id); //调用iframe页面中的函数
                                    } else if (type == 1) {
                                        //jumpUrl字符串中不含有geoserver字符串
                                        childWindow.load3Dtiles(previewUrl, data.id);
                                    } else if (type == 2) {
                                        childWindow.load3DGeoJson(previewUrl, data.id);
                                    }
                                } else {
                                    setTimeout(function() {
                                        layer.msg("图层预览失败，请检查图层对应的要素内容是否禁用或不存在", {
                                            icon: 5
                                        });
                                    }, 1000);
                                    setTimeout(function() {
                                        layerConfigObj.del(data);
                                        childWindow.removeEntityById(data.id);
                                        var treeData = openTree(getData(sceneId), data.id); //解决节点操作后重新绘制树只显示根节点的问题——其实就是对后台返回数据做了处理
                                        tree.reload('treeId', {
                                            data: treeData
                                        });
                                    }, 3000);
                                }
                            }
                            /*     error:function (err) {
                                     layer.msg("图层预览失败，请检查图层对应的要素格式是否合法", {icon: 5});
                                     layer.close(loading);
                                 }*/
                    });
                    // throw new TypeError("失败");
                } catch (err) {
                    layer.msg("渲染失败，请检查服务地址是否合法", {
                        icon: 5
                    });
                }
            };
            //测试要素是否禁用
            layerConfigObj.elementTest = function(data) {
                $.ajax({
                    url: "/one/scene/elementInfo",
                    type: "GET",
                    dataType: "json",
                    contentType: "application/json; charset=UTF-8",
                    data: {
                        id: data.id
                    },
                    async: false,
                    success: function(result) {
                        if (result.errorCode === '401') {
                            loginStatusIntercept(result.msg)
                            return
                        }
                        if (result.errorCode == 0) {
                            //启用状态
                            if (data.checked === true) {
                                childWindow.centerEntityById(data.id);
                            }
                            //禁用状态
                            else if (data.checked === false) {
                                layer.msg("禁用状态不可预览，请先启用图层", {
                                    icon: 5
                                });
                            }
                        } else {
                            setTimeout(function() {
                                layer.msg("图层预览失败，请检查图层对应的要素内容是否禁用或不存在", {
                                    icon: 5
                                });
                            }, 1000);
                            setTimeout(function() {
                                layerConfigObj.del(data);
                                childWindow.removeEntityById(data.id);
                                var treeData = openTree(getData(sceneId), data.id); //解决节点操作后重新绘制树只显示根节点的问题——其实就是对后台返回数据做了处理
                                tree.reload('treeId', {
                                    data: treeData
                                });
                            }, 3000);

                        }
                    },
                    error: function(err) {
                        layer.msg("渲染失败，请检查要素是否合法", {
                            icon: 5
                        });
                    }
                });
            };
            //进入场景后将自动飞行至设置的初始视角
            layerConfigObj.enterSceneSet = function() {
                childWindow = $("#layer_iframe")[0].contentWindow; //调用iframe页面
                var viewer = childWindow.viewer;

                function showExtent(cfg) {
                    viewer.mars.centerAt(cfg, {
                        isWgs84: true
                    });
                }
                var getExtent = sceneDetail.angle;
                var bookmarkGet = JSON.parse(getExtent);
                showExtent(bookmarkGet);
            };
            //图层添加时复选框状态判断
            table.on('radio(user-table)', function(obj) {
                featureId = obj.data.id;
                featureType = obj.data.type;
                featureName = obj.data.elementName;
                // console.log(obj.checked); //当前是否选中状态
                // console.log(obj.data); //选中行的相关数据
                // console.log(obj.type); //如果触发的是全选，则为：all，如果触发的是单选，则为：one
                // console.log(table.checkStatus('user-table').data); // 获取表格中选中行的数据
            });

            function getData(sceneId) {
                $.ajax({
                    url: '/one/scene/element/list/all' + '?sceneId=' + sceneId,
                    dataType: 'json',
                    type: 'get',
                    async: false,
                    // data:JSON.stringify({sceneId:featureId}),
                    success: function(result) {
                        if (result.errorCode === '401') {
                            loginStatusIntercept(result.msg)
                            return
                        }
                        var treeData = result.data;
                        var stringTree = JSON.stringify(treeData);
                        var dataStr = stringTree.replace(/layerName/g, "title");
                        var dataS = dataStr.replace(/status/g, "checked");
                        dataT = JSON.parse(dataS);
                    }
                });
                // dataT[0].spread=true;
                return dataT;
            }
            //树重载
            window.reloadTree = function treeReload() {
                tree.reload('treeId', {
                    data: getData(sceneId)
                });
            };


            tree.render({
                elem: '#treeLi',
                data: getData(sceneId),
                id: 'treeId',
                showCheckbox: true //是否显示复选框
                    ,
                onlyIconControl: true //控制点击父节点的title子节点不收缩，点击图标时进行收缩
                    // ,customOperate: true //自定义设置树操作
                    ,
                limitNodeAddLevel: 2 //设置第X级节点不允许添加操作
                    ,
                limitNodeDelLevel: 1 //设置第X级节点不允许删除操作
                    ,
                showLine: false //是否开启连接线。默认 true，若设为 false，则节点左侧出现三角图标。
                    ,
                edit: ['update', 'del', 'moveup', 'movedown'] //操作节点的图标
                    ,
                isJump: true //是否允许点击节点时弹出新窗口跳转
                    ,
                click: function(obj) {
                    var data = obj.data;
                    console.log(obj.data.sort);
                    //先检查对应要素是否被禁用或者删除
                    layerConfigObj.elementTest(data);
                },
                oncheck: function(obj) {
                    checkedType = obj.checked;
                    var data = obj.data;
                    var featureContent = data.elementContent;
                    var featureType = data.type;
                    if (checkedType === false) { //关闭节点
                        layerConfigObj.close(data, checkedType);
                        childWindow.removeEntityById(data.id);
                    } else if (checkedType === true) { //启用节点
                        layerConfigObj.preview(obj);
                        layerConfigObj.start(data, checkedType);
                    }
                },
                operate: function(obj, oldvalue) {
                    var type = obj.type; //得到操作类型：add、edit、del、moveup、movedown
                    var data = obj.data; //得到当前节点的数据
                    // var elem = obj.elem;//得到当前节点元素
                    var deptId = data.id; //得到节点索引
                    if (type === 'add') { //增加节点
                        layerConfigObj.add(data);
                    } else if (type === 'update') { //修改节点
                        if (obj.data.title == "未命名") {
                            layer.msg("未输入", {
                                icon: 5
                            });
                            var txt = obj.elem.find(".layui-tree-txt");
                            txt.html(oldvalue)
                        } else {
                            layerConfigObj.update(data, obj, oldvalue);
                        }
                    } else if (type === 'del') { //删除节点
                        layerConfigObj.del(data);
                        // childWindow.clear();
                        childWindow.removeEntityById(data.id);
                    } else if (type === 'moveup') { //上移节点
                        layerConfigObj.moveup(data);
                    } else if (type === 'movedown') { //下移节点
                        layerConfigObj.movedown(data);
                    }
                }
            });
            //执行节点勾选
            // tree.setChecked('treeId', 1); //单个勾选 id 为 1 的节点
            // tree.setChecked('treeId', [9,26]); //批量勾选 id 为 2、3 的节点
            //获得选中的节点
            // var checkData = tree.getChecked('treeId');
            // console.log(checkData);
            let cols = [
                [{
                    type: 'radio',
                    align: 'center'
                }, {
                    title: '要素名称',
                    field: 'elementName',
                    align: 'center',
                    width: 300
                }, {
                    title: '要素类别',
                    field: 'type',
                    align: 'center',
                    templet: '#data-type',
                    width: 300
                }]
            ];


            table.render({
                elem: '#user-table',
                url: '/one/element/list',
                method: 'post',
                contentType: 'application/json',
                where: {
                    status: "1",
                    requestSet: "2"
                },
                request: {
                    pageName: 'pageNo' //页码的参数名称，默认：page
                        ,
                    limitName: 'pageSize' //每页数据量的参数名，默认：limit
                },
                parseData: function(res) { //res 即为原始返回的数据
                    return {
                        "createTime": null,
                        "createBy": null,
                        "updateTime": null,
                        "updateBy": null,
                        "remark": null,
                        "code": 200,
                        "msg": "...",
                        "count": res.data.total,
                        "data": res.data.list
                    }
                },
                id: 'user-table',
                page: true,
                cols: cols,
                skin: 'line',
                even: true, //开启隔行背景
                response: {
                    statusCode: 200 //成功的状态码，默认：0
                },
            });

            /*       //按钮事件
                   util.event('user-table', {
                       getChecked: function(othis){
                           var checkedData = tree.getChecked('treeId'); //获取选中节点的数据
                           layer.alert(JSON.stringify(checkedData), {shade:0});
                           console.log(checkedData);
                       }
                   });*/

            //上移图层
            layerConfigObj.moveup = function(data) {
                // tree.reload('treeId', {data: getData(sceneId)});
                var upId = data.id;
                var forTree = function(arr, id) {
                    for (var i = 0; i < arr.length; i++) {
                        var item = arr[i];
                        var itemUp = arr[i - 1];
                        if ((item.id === id) && (i !== 0)) {
                            item.sort = item.sort - 1;
                            itemUp.sort = itemUp.sort + 1;
                            $.ajax({
                                url: "/one/scene/element",
                                type: "PUT",
                                dataType: "json",
                                contentType: "application/json; charset=UTF-8",
                                data: JSON.stringify({
                                    elementId: item.elementId,
                                    id: item.id,
                                    sceneId: sceneId,
                                    layerName: item.title,
                                    sort: item.sort,
                                    status: item.checked ? 1 : 0,
                                    type: item.type
                                }),
                            });
                            $.ajax({
                                url: "/one/scene/element",
                                type: "PUT",
                                dataType: "json",
                                contentType: "application/json; charset=UTF-8",
                                data: JSON.stringify({
                                    elementId: itemUp.elementId,
                                    id: itemUp.id,
                                    sceneId: sceneId,
                                    layerName: itemUp.title,
                                    sort: itemUp.sort,
                                    status: itemUp.checked ? 1 : 0,
                                    type: itemUp.type
                                }),
                                success: function(result) {
                                    if (result.errorCode === '401') {
                                            loginStatusIntercept(result.msg)
                                            return
                                        }
                                    if (result.errorCode == 0) {
                                        layer.msg("上移图层成功", {
                                            icon: 6
                                        });
                                        // var treeData = openTree(getData(),data.id);//解决节点操作后重新绘制树只显示根节点的问题——其实就是对后台返回数据做了处理
                                        tree.reload('treeId', {
                                            data: getData(sceneId)
                                        });
                                    } else {
                                        layer.msg("上移图层失败", {
                                            icon: 5
                                        });
                                    }
                                }
                            });
                            break;
                        } else if ((item.id === id) && (i === 0)) {
                            break;
                        }
                    }
                    return arr;
                };
                forTree(dataT, upId);
                // tree.reload('treeId', {data: getData(sceneId)});
            };
            // ..树展开，父节点spread字段赋值true
            var openTree = function(treeData, objId) {
                var nodeId = familyTree(treeData, objId);

                function each(data) {
                    try {
                        data.forEach(e => {
                            if (nodeId.indexOf(e.id) != -1) {
                                e.spread = true;
                            }
                            if (e.children.length > 0) {
                                each(e.children);
                            }
                        })
                    } catch (e) {
                        console.log(1);
                    }
                }
                each(treeData);
                return treeData;
            };
            // 查找一个节点的所有父节点
            var familyTree = function(arr1, id) {
                var temp = [];
                var forFn = function(arr, id) {
                    for (var i = 0; i < arr.length; i++) {
                        var item = arr[i];
                        if (item.id === id) {
                            temp.push(item.id);
                            forFn(arr1, item.parentId);
                            break;
                        } else {
                            if (item.children) {
                                forFn(item.children, id);
                            }
                        }
                    }
                };
                forFn(arr1, id);
                return temp;
            };
            //下移图层
            layerConfigObj.movedown = function(data) {
                var downId = data.id;
                var forTree = function(arr, id) {
                    for (var i = 0; i < arr.length; i++) {
                        var item = arr[i];
                        var itemDown = arr[i + 1];
                        if ((item.id === id) && (i !== arr.length - 1)) {
                            item.sort = item.sort + 1;
                            itemDown.sort = itemDown.sort - 1;
                            $.ajax({
                                url: "/one/scene/element",
                                type: "PUT",
                                dataType: "json",
                                contentType: "application/json; charset=UTF-8",
                                data: JSON.stringify({
                                    elementId: item.elementId,
                                    id: item.id,
                                    sceneId: sceneId,
                                    layerName: item.title,
                                    sort: item.sort,
                                    status: item.checked ? 1 : 0,
                                    type: item.type
                                }),
                            });
                            $.ajax({
                                url: "/one/scene/element",
                                type: "PUT",
                                dataType: "json",
                                contentType: "application/json; charset=UTF-8",
                                data: JSON.stringify({
                                    elementId: itemDown.elementId,
                                    id: itemDown.id,
                                    sceneId: sceneId,
                                    layerName: itemDown.title,
                                    sort: itemDown.sort,
                                    status: itemDown.checked ? 1 : 0,
                                    type: itemDown.type
                                }),
                                success: function(result) {
                                    if (result.errorCode === '401') {
                                            loginStatusIntercept(result.msg)
                                            return
                                        }
                                    if (result.errorCode == 0) {
                                        layer.msg("下移图层成功", {
                                            icon: 6
                                        });
                                        // var treeData = openTree(getData(),data.id);//解决节点操作后重新绘制树只显示根节点的问题——其实就是对后台返回数据做了处理
                                        tree.reload('treeId', {
                                            data: getData(sceneId)
                                        });
                                    } else {
                                        layer.msg("下移图层失败", {
                                            icon: 5
                                        });
                                    }
                                }
                            });
                            break;
                        } else {
                            if (i === arr.length - 1) {
                                break;
                            }
                        }
                    }
                    return arr;
                };
                forTree(dataT, downId);
                // tree.reload('treeId', {data: getData(sceneId)});
            };

            //添加图层
            layerConfigObj.add = function(data) {

                if (data.children.length > 0) {
                    var arr = dataT;
                    var sortMax;
                    for (var i = 0; i < arr.length; i++) {
                        var item = arr[i];
                        if (item.id === data.id) {
                            var itemChild = item.children[item.children.length - 1];
                            sortMax = itemChild.sort + 1;
                            break
                        } else {}
                    }
                    layer.open({
                        type: 1,
                        title: '添加图层',
                        shade: 0.1,
                        area: ['50%', '90%'],
                        content: $('#service-window'),
                        resize: true,
                        btn: ['确定', '取消'],
                        success: function(layero, index) {
                            $('#feature-name').show();
                            $('#feature-detail').show();
                            $('#user').show();
                            $('#research').show();
                        },
                        yes: function(index, layero) {
                            $.ajax({
                                url: "/one/layer",
                                type: "POST",
                                dataType: "json",
                                contentType: "application/json; charset=UTF-8",
                                data: JSON.stringify({
                                    elementId: featureId,
                                    isDir: '0',
                                    parentId: data.id,
                                    layerName: $('#feature-name').val(),
                                    remark: $('#feature-detail').val(),
                                    sort: sortMax,
                                    status: 1,
                                    requestSet: "2",
                                }),
                                success: function(result) {
                                    if (result.errorCode === '401') {
                                            loginStatusIntercept(result.msg)
                                            return
                                        }
                                    if (result.errorCode == 0) {
                                        layer.msg("增加成功", {
                                            icon: 6
                                        }, function(i) {
                                            layer.close(i);
                                            layer.close(index); //关闭弹出层
                                        });
                                        var treeData = openTree(getData(), data.id);
                                        tree.reload('treeId', {
                                            data: treeData
                                        });
                                    } else {
                                        layer.msg("添加失败", {
                                            icon: 5
                                        });
                                    }
                                }
                            });
                        }
                    });
                } else if (data.children.length === 0) {
                    layer.open({
                        type: 1,
                        title: '添加图层',
                        shade: 0.1,
                        area: ['50%', '90%'],
                        content: $('#service-window'),
                        resize: true,
                        btn: ['确定', '取消'],
                        success: function(layero, index) {
                            $('#feature-name').show();
                            $('#feature-detail').show();
                            $('#user').show();
                            $('#research').show();
                        },
                        yes: function(index, layero) {
                            $.ajax({
                                url: "/one/layer",
                                type: "POST",
                                dataType: "json",
                                contentType: "application/json; charset=UTF-8",
                                data: JSON.stringify({
                                    elementId: featureId,
                                    isDir: '0',
                                    parentId: data.id,
                                    layerName: $('#feature-name').val(),
                                    remark: $('#feature-detail').val(),
                                    sort: 0,
                                    status: 1,
                                    requestSet: "2",
                                }),
                                success: function(result) {
                                    if (result.errorCode === '401') {
                                            loginStatusIntercept(result.msg)
                                            return
                                        }
                                    if (result.errorCode == 0) {
                                        layer.msg("增加成功", {
                                            icon: 6
                                        }, function(i) {
                                            layer.close(i);
                                            layer.close(index); //关闭弹出层
                                        });
                                        var treeData = openTree(getData(), data.id);
                                        tree.reload('treeId', {
                                            data: treeData
                                        });
                                    } else {
                                        layer.msg("添加失败", {
                                            icon: 5
                                        });
                                    }
                                }
                            });
                        }
                    });
                }
            };
            //要素查询
            /*        $.ajax({
                        url:"/selectServer",
                        type:"GET",
                        dataType:"json",
                        success:function(result){
                            var list = result;    //返回的数据
                            var server = document.getElementById("server"); //server为select定义的id
                            for(var p in list){
                                var option = document.createElement("option");  // 创建添加option属性
                                option.setAttribute("value",p); // 给option的value添加值
                                option.innerText=list[p];     // 打印option对应的纯文本
                                server.appendChild(option);           //给select添加option子标签
                                form.render("select");            // 刷性select，显示出数据
                            }
                        }
                    });*/
            form.on('select(selectFeature)', function(data) {
                // console.log(this.innerText); //得到被选中文本
                // console.log(data.value); //得到被选中的值
                //执行重载
                var demoReload = $('#demoReload');
                var selectValue = data.value; //得到被选中的值
                if (selectValue === "") {
                    table.reload('user-table', {
                        where: { //设定异步数据接口的额外参数，任意设
                            status: "1",
                            elementName: demoReload.val(),
                            requestSet: "2",
                        },
                        page: {
                            curr: 1 //假设你是第三页，那你传参数就传2啊。就是传你想的要的页数-1
                        }
                    });
                    // form.render('select');
                } else {
                    table.reload('user-table', {
                        page: {
                            curr: 1 //重新从第 1 页开始
                        },
                        where: {
                            status: "1",
                            requestSet: "2",
                            elementName: demoReload.val(),
                            type: JSON.parse(selectValue)
                        }
                    }, 'data');
                    form.render('select');
                }
            });
            $('#featureSearch').on('click', function() {

                var selectValue = $("#selectFeature").val(); //得到被选中的值
                var demoReload = $('#demoReload').val();
                if ((demoReload === "") && (selectValue !== "")) {
                    //执行重载
                    table.reload('user-table', {
                        page: {
                            curr: 1 //重新从第 1 页开始
                        },
                        where: {
                            status: "1",
                            requestSet: "2",
                            type: selectValue,
                        }
                    }, 'data');
                    return;
                } else if ((selectValue === "") && (demoReload !== "")) {
                    //执行重载
                    table.reload('user-table', {
                        page: {
                            curr: 1 //重新从第 1 页开始
                        },
                        where: {
                            status: "1",
                            requestSet: "2",

                            elementName: demoReload
                        }
                    }, 'data');
                    return;
                } else if ((selectValue === "") && (demoReload === "")) {
                    //执行重载
                    table.reload('user-table', {
                        page: {
                            curr: 1 //重新从第 1 页开始
                        },
                        where: {
                            status: "1",
                            requestSet: "2",
                        }
                    }, 'data');
                    return;
                } else {
                    //执行重载
                    table.reload('user-table', {
                        page: {
                            curr: 1 //重新从第 1 页开始
                        },
                        where: {
                            status: "1",
                            requestSet: "2",
                            type: selectValue,
                            elementName: demoReload
                        }
                    }, 'data');
                }
            });

            layerConfigObj.update = function(data, obj, oldvalue) {

                var txt = obj.elem.find(".layui-tree-txt");

                var name = data.title;
                if (!name || name.length > 50) {
                    layer.msg("名称不能超过50个字", {
                        icon: 5
                    });
                    $(txt[0]).html(oldvalue)
                    return;
                }
                $.ajax({
                    url: "/one/scene/element",
                    type: "PUT",
                    dataType: "json",
                    contentType: "application/json; charset=UTF-8",
                    data: JSON.stringify({
                        elementId: data.elementId,
                        id: data.id,
                        sceneId: sceneId,
                        layerName: data.title,
                        sort: data.sort,
                        status: data.checked ? 1 : 0,
                        type: data.type
                    }),
                    success: function(result) {
                        if (result.errorCode === '401') {
                            loginStatusIntercept(result.msg)
                            return
                        }
                        if (result.errorCode == 0) {
                            layer.msg("修改成功", {
                                icon: 6
                            });
                        } else {
                            $(txt[0]).html(oldvalue)
                            layer.msg("修改失败", {
                                icon: 5
                            });
                        }
                    }
                });
            };
            layerConfigObj.del = function(data) {
                var id = data.id;
                var arrNew = new Array(); //创建了一个长度为0的数组对象。
                arrNew.push(id);
                //删除场景图层
                $.ajax({
                    url: "/one/scene/element?" + "ids=" + arrNew.join("&ids="),
                    type: "DELETE",
                    dataType: "json",
                    contentType: "application/json; charset=UTF-8",
                    success: function(result) {
                        if (result.errorCode === '401') {
                                loginStatusIntercept(result.msg)
                                return
                            }
                        if (result.errorCode == 0) {
                            layer.msg("删除图层成功", {
                                icon: 6
                            });
                        } else {
                            layer.msg("删除图层失败", {
                                icon: 5
                            });
                        }

                    }
                });
                /*                //同步删除要素管理中的空间模型
                                let ids_elementId = data.elementId;
                                $.ajax({
                                    url: "/one/element/model",
                                    type: "DELETE",
                                    data:{ids:ids_elementId},
                                    dataType: "json",
                                    success: function(data){
                                    }
                                });*/
                var arr = dataT;
                //调整删除后的排序
                for (var i = 0; i < arr.length; i++) {
                    var item = arr[i];
                    if (item.sort > data.sort) {
                        item.sort = item.sort - 1;

                        $.ajax({
                            url: "/one/scene/element",
                            type: "PUT",
                            dataType: "json",
                            contentType: "application/json; charset=UTF-8",
                            data: JSON.stringify({
                                elementId: item.elementId,
                                id: item.id,
                                sceneId: sceneId,
                                layerName: item.title,
                                sort: item.sort,
                                status: item.checked ? 1 : 0,
                                type: item.type
                            }),
                            success: function(result) {
                                if (result.errorCode === '401') {
                                    loginStatusIntercept(result.msg)
                                    return
                                }
                                if (result.errorCode == 0) {
                                    // layer.msg("删除图层成功", {icon: 6});
                                    // childWindow.clear();
                                    /*var treeData = openTree(getData(),data.id);//解决节点操作后重新绘制树只显示根节点的问题——其实就是对后台返回数据做了处理
                                    tree.reload('treeId', {data: treeData});*/
                                } else {
                                    // layer.msg("删除图层失败", {icon: 5});
                                }
                            }
                        });
                    } else {

                    }
                }
                // tree.reload('treeId', {data: getData(sceneId)});
            };


            //添加图层
            $('#search_add').on('click', function() {

                var arr = dataT;
                var sortMax;
                if (arr.length > 0) {
                    sortMax = arr[arr.length - 1].sort + 1;
                } else if (arr.length === 0) {
                    sortMax = 0;
                }

                layer.open({
                    type: 1,
                    title: '通过搜索添加',
                    shade: 0.1,
                    area: ['50%', '90%'],
                    content: $('#service-window'),
                    resize: true,
                    btn: ['确定', '取消'],
                    success: function(layero, index) {
                        $('#user').show();
                        $('#research').show();
                    },
                    yes: function(index) {
                        if (!canSearchAdd) return;
                        canSearchAdd = false;
                        if (!featureId) {
                            layer.msg("请勾选要素", {
                                icon: 5
                            });
                        } else {

                            $.ajax({
                                url: "/one/scene/element",
                                type: "POST",
                                dataType: "json",
                                contentType: "application/json; charset=UTF-8",
                                data: JSON.stringify({
                                    elementId: featureId,
                                    layerName: featureName,
                                    sceneId: sceneId,
                                    sort: sortMax,
                                    status: 1,
                                    type: featureType
                                }),
                                success: function(result) {
                                    if (result.errorCode === '401') {
                                        loginStatusIntercept(result.msg)
                                        return
                                    }
                                    setTimeout(() => {
                                        canSearchAdd = true;
                                    }, 4000)
                                    if (result.success) {
                                        layer.msg("添加成功", {
                                            icon: 6
                                        }, function(i) {
                                            layer.close(i);
                                            layer.close(index); //关闭弹出层
                                            setTimeout(function() {
                                                tree.reload('treeId', {
                                                    data: getData(sceneId)
                                                });
                                            }, 2000);
                                            $("#service-add")[0].reset(); //重置form
                                            table.reload('user-table');
                                            featureId = undefined;
                                        });
                                    } else {
                                        layer.msg("添加失败,失败原因：" + result.msg, {
                                            icon: 5
                                        });
                                    }
                                }
                            });
                        }
                        // table.reload('user-table');
                    },
                    btn2: function(index, layero) {
                        //按钮【按钮二】的回调
                        $('#demoReload').val("")
                        featureId = undefined;
                        table.reload('user-table', {
                            page: {
                                curr: 1 //重新从第 1 页开始
                            },
                            where: {
                                status: "1",
                                requestSet: "2",
                            }
                        }, 'data');
                        //return false 开启该代码可禁止点击该按钮关闭
                    },
                    cancel: function() {
                        $('#demoReload').val("")
                        featureId = undefined;
                        //右上角关闭回调
                        table.reload('user-table', {
                            page: {
                                curr: 1 //重新从第 1 页开始
                            },
                            where: {
                                status: "1",
                                requestSet: "2",
                            }
                        }, 'data');
                        //return false 开启该代码可禁止点击该按钮关闭
                    }
                });
            });

            //创建空间模型
            $('#spatialModel_add').on('click', function() {

                childWindow.spatialModelCreate();
                var arr = dataT;
                var sortMax;
                if (arr.length > 0) {
                    sortMax = arr[arr.length - 1].sort + 1;
                } else if (arr.length === 0) {
                    sortMax = 0;
                }
                sessionStorage.feature_sceneId = sceneId;
                sessionStorage.feature_sortMax = sortMax;
                /*childWindow.onload = function (){
                    debugger
                    var win=$("#layer_iframe")[0].contentWindow.document.getElementById("btn_plot_savefile");
                    console.log(win);
                };
*/
                /*  $('#layer_iframe').contentDocument.getElementById("btn_plot_savefile").οnclick=function(){
                               alert(123);
                           };*/
                // $("#layer_iframe").contents().find("#btn_plot_savefile").css('display','none');
                // $(window.frames["layer_iframe"].frames["iframe2"].document).find("input:radio").attr("checked","true");

            });
        });
    };
</script>

</html>